//
//  ST_PairsPlayerView.swift
//  btvideo
//
//  Created by mac on 2020/1/3.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import KTVHTTPCache

class ST_PairsPlayerView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        add_notifications()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     override func layoutSubviews() {
        super.layoutSubviews()
        self.playerLayer?.frame = self.bounds
    }
    
    //    MARK: -  player properties
    //    播放中
    fileprivate var playing = false

    fileprivate var player:AVPlayer?

    fileprivate var time_observer:Any?

    fileprivate var playerItem:AVPlayerItem?

    fileprivate var playerLayer:AVPlayerLayer?

    //    MARK: - Method
    func play(url:URL) {
     
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
        }catch{
            print("AVAudioSession.Category.playback Error")
        }
        
        guard let pUrl = KTVHTTPCache.proxyURL(withOriginalURL: url) else{
           print("缓存方案 创建代理Url失败：\(url)")
           return
        }
        
        let playerItem = AVPlayerItem(url: pUrl)
        
        self.playerItem = playerItem

        //创建ACplayer：负责视频播放
        self.player = AVPlayer.init(playerItem: playerItem)
        self.player?.isMuted = true
        self.player?.rate = 1.0//播放速度 播放前设置
        //创建显示视频的图层
        let playerLayer = AVPlayerLayer.init(player: player)
        playerLayer.videoGravity = .resizeAspectFill
        playerLayer.frame = self.bounds
        self.playerLayer = playerLayer

        self.layer.addSublayer(playerLayer)
        
        guard let player = self.player else { return  }
        
        player.play()
        
        playing = true
        
    }
        
    func stop(){
        
        playing = false
        
        guard let playerLayer = self.playerLayer else { return  }
        
        playerLayer.removeFromSuperlayer()
        self.playerLayer = nil
        
        guard let player = self.player else { return  }
        
        player.pause()
        
        if  let timerObs = self.time_observer{
            player.removeTimeObserver(timerObs)
        }
        
        self.player = nil
    }

}



//MARK: - Notification
extension ST_PairsPlayerView{
    
    
    func add_notifications()  {
            
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: .main) { [weak self] noti in
            
            if let playerItem = noti.object as? AVPlayerItem{
                
                if let currentItem = self?.player?.currentItem,playerItem == currentItem{
                    
//                    print("FWPlayer---播放完成，重新播放")
                    
                    self?.player?.seek(to: CMTime.zero)
                    self?.player?.play()
                    
                    return
                }
            }
        }
        
    }
}
